package com.ezops.poc.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.ezops.poc.bo.DataException;
import com.ezops.poc.validations.EzopsValidationException;
import com.ezops.poc.validations.result.FieldValidationError;

@Repository(value = "exceptionDAO")
public class DataExceptionDAO {

	private static final String COMMA_SEPARATED_COLUMNS = "EZOPS_ID,TRADEID,ERRORMESSAE,FIELDNAME,FILENAME,CLIENTID,ACTION,ASSET_ID";

	private static final String INSERT_EXCEPTION_QUERY = "INSERT INTO EZOPSDB.DATA_EXCEPTION("
			+ COMMA_SEPARATED_COLUMNS + ") VALUES (?,?,?,?,?,?,?,?)";

	private static final Logger log = LoggerFactory
			.getLogger(DataExceptionDAO.class);

	@Autowired
	private JdbcTemplate jdbcTemplate;

	public DataExceptionDAO() {
	}

	public void persist(EzopsValidationException exceptions) {
		for (FieldValidationError error : exceptions.getFieldErrors()) {
			DataException exception = new DataException(
					error.getErrorMessage(), error.getFieldName(), exceptions
							.getTradeIdentifier().getFileName(), exceptions
							.getTradeIdentifier().getClientId(), exceptions
							.getTradeIdentifier().getAction(), exceptions
							.getTradeIdentifier().getClientTradeId(),
					exceptions.getTradeIdentifier().getAssetId(), exceptions
							.getTradeIdentifier().getEzopsId());
			persistException(exception);
		}

	}

	public void persistException(DataException transientModel) {
		log.info("Adding exception record to database. trade id: "
				+ transientModel.getTradeId() + " action: "
				+ transientModel.getAction());
		jdbcTemplate.update(INSERT_EXCEPTION_QUERY,
				getColumnValues(transientModel));
	}

	/**
	 * 
	 * @param model
	 * @return
	 */
	private Object[] getColumnValues(DataException model) {
		return new Object[] { model.getEzopId(),model.getTradeId(), model.getErrorMessae(),
				model.getFieldName(), model.getFileName(), model.getClientId(),
				model.getAction(), model.getAssetId() };

	}
}
